package io.github.mymonstercat.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.util.Objects;

public class FileUtils{

    public static String upload(MultipartFile file, String windowPath, String linuxPath) {
        // 获取文件名称
        String name = Objects.requireNonNull(file.getOriginalFilename()).replaceAll(".*[\\\\/]", "");
        String path;
        // 获取系统标识
        String osName = System.getProperty("os.name");
        if (osName.startsWith("Windows")) {
            path = windowPath;
        } else {
            path = linuxPath;
        }
        // 文件上传到指定地点
        try (FileInputStream inputStream = (FileInputStream) file.getInputStream(); OutputStream outputStream = new FileOutputStream(path + name)) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
        return path + name;
    }

    public static String getPath(String windowPath, String linuxPath) {
        String path;
        // 获取系统标识
        String osName = System.getProperty("os.name");
        if (osName.startsWith("Windows")) {
            path = windowPath;
        } else {
            path = linuxPath;
        }
        return path;
    }

}
